#!/usr/bin/env tsx

/**
 * 为管理员账户分配权限脚本
 * 使用方法: npx tsx scripts/assign-admin-permissions.ts
 */

import { getDb } from '../src/lib/db/index';
import { User, Role, Permission } from '../src/lib/db/auth-schema';

async function main() {
  try {
    console.log('🚀 开始为管理员分配权限...');
    
    // 连接数据库
    const db = await getDb();
    
    // 查找管理员用户
    const adminResult = await db.findOne('users', { email: 'admin@admin.com' });
    if (!adminResult.success || !adminResult.data) {
      console.error('❌ 未找到管理员账户');
      process.exit(1);
    }
    
    const adminUser = adminResult.data as User;
    console.log('✅ 找到管理员账户:', adminUser.email);
    
    // 查找admin角色
    const adminRoleResult = await db.findOne('roles', { name: 'admin' });
    if (!adminRoleResult.success || !adminRoleResult.data) {
      console.error('❌ 未找到admin角色');
      process.exit(1);
    }
    
    const adminRole = adminRoleResult.data as Role;
    console.log('✅ 找到admin角色:', adminRole.display_name);
    
    // 检查用户是否已有admin角色
    const existingUserRoleResult = await db.findOne('user_roles', {
      user_id: adminUser.id,
      role_id: adminRole.id
    });
    
    if (!existingUserRoleResult.success || !existingUserRoleResult.data) {
      // 为管理员分配admin角色
      const now = new Date().toISOString();
      const userRoleResult = await db.create('user_roles', {
        id: `user_role_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`,
        user_id: adminUser.id,
        role_id: adminRole.id,
        assigned_by: adminUser.id,
        assigned_at: now
      });
      
      if (userRoleResult.success) {
        console.log('✅ 已为管理员分配admin角色');
      } else {
        console.error('❌ 分配admin角色失败');
      }
    } else {
      console.log('✅ 管理员已拥有admin角色');
    }
    
    // 获取所有权限
    const permissionsResult = await db.findMany('permissions', {});
    if (!permissionsResult.success) {
      console.error('❌ 获取权限列表失败');
      process.exit(1);
    }
    
    const permissions = (permissionsResult.data || []) as Permission[];
    console.log(`✅ 找到 ${permissions.length} 个权限`);
    
    // 为admin角色分配所有权限
    const now = new Date().toISOString();
    let assignedCount = 0;
    
    for (const permission of permissions) {
      const existingRolePermissionResult = await db.findOne('role_permissions', {
        role_id: adminRole.id,
        permission_id: permission.id
      });
      
      if (!existingRolePermissionResult.success || !existingRolePermissionResult.data) {
        const rolePermissionResult = await db.create('role_permissions', {
          id: `role_perm_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`,
          role_id: adminRole.id,
          permission_id: permission.id,
          granted_by: adminUser.id,
          granted_at: now
        });
        
        if (rolePermissionResult.success) {
          assignedCount++;
        }
      }
    }
    
    console.log(`✅ 为admin角色分配了 ${assignedCount} 个新权限`);
    
    console.log('\n✅ 管理员权限分配完成！');
    console.log('\n📋 管理员账户信息:');
    console.log('   邮箱: admin@admin.com');
    console.log('   密码: admin123456');
    console.log('   角色: admin');
    console.log(`   权限数量: ${permissions.length}`);
    
    process.exit(0);
    
  } catch (error: any) {
    console.error('\n❌ 分配权限失败:', error.message);
    console.error(error.stack);
    process.exit(1);
  }
}

// 运行脚本
if (require.main === module) {
  main();
}

export { main };